<?php
namespace App\GraphQL\Mutations\Ad;

use App\Models\Ad;
use App\Models\User;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

class Update
{

    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        $id = $args['id'];
        $data = $args['input'];
        $data['agent_user_id']=$data['agent_user_id']?:0;
        $data['cate']=$data['agent_user_id']?'PRIVATE': 'NORMAL';
        $ad = $this->validate($id, $data);
        // 更新广告
        $ad->update($data);
        return [
            'status' => '200',
            'message' => '更新成功'
        ];
    }

    public function validate($id, $data)
    {
        $cates = [
            'NORMAL',
            'PRIVATE'
        ];
        $rules = [
            'name' => [
                'required',
                'max:18'
            ],
            'cate' => [
                'required',
                Rule::in($cates)
            ],
            'agent_user_id'=>[
                'nullable',
                'numeric'
            ],
            'redirect_url' => [
                'nullable',
                'url'
            ],
            'cover_url' => [
                'required',
                'url'
            ],
            'price'=>[
                'nullable',
                'numeric'
            ],
            'expired_at'=>[
                'required',
                'date'
            ]
        ];
        $messages = [
            'name.required' => '名称不能为空',
            'name.max' => '名称不能超过18个字',
            'cate.required' => '分类不能为空',
            'cover_url.required' => '封面不能为空',
            'cover_url.url' => '封面为url地址',
            'cate.in' => '分类不能超出限制',
            'agent_user_id.numeric' => '代理ID为数值',
            'price.numeric' => '价格为数值',
            'expired_at.required'=>'过期时间不能为空',
            'expired_at.date'=>'过期时间为日期',
            'redirect_url.url' => '跳转地址为url',
        ];
        $validate = Validator::make($data, $rules, $messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        // 代理
        if($data['agent_user_id']){
            $agent = User::find($data['agent_user_id']);
            if(!$agent && $agent->role_code !== 'AGENT'){
                throw new \Exception('代理不存在');
            }
        }
        $old = Ad::find($id);
        if (! $old) {
            throw new \Exception('广告不存在!');
        }
        return $old;
    }
}
